<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>法律咨询</title>
    <link rel="stylesheet" href="../../css/element.css">
    <link rel="stylesheet" href="../../css/base.css">

    <style>
        .message {
            padding: 5px;
            margin: 5px;
            border-radius: 5px;
        }
        .user-message {
            background-color: #DCF8C6;
            text-align: right;
        }
        .system-message {
            background-color: #F0F0F0;
            text-align: left;
        }
        .user-avatar {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            margin-right: 10px;
            vertical-align: middle;
        }
        .el-card__body {
            max-height: 350px; /* 设置最大高度 */
            overflow: hidden; /* 隐藏溢出部分 */
            text-overflow: ellipsis; /* 使用省略号代替溢出部分 */
            white-space: nowrap; /* 不换行 */
        }
    </style>
</head>
<body class="frame-body">
<div id="wrapper" v-cloak>
    <el-row>
        <el-col :span="24" :offset="2">

            <div style="margin: 10px 0 50px 0; display: flex; flex-wrap: wrap;">

                <el-col :span="6" v-for="(lawyer, index) in lawyerList" :key="index" style="margin-bottom: 10px;">
                    <el-card class="box-card" style="height: 300px;  width: 200px; margin-left: 10px">
                        <div style="text-align: center;">
                            <img v-if="lawyer.avatar" :src="['/files/' + lawyer.avatar]" style="height: 100px;width: 100px;display: block" class="avatar">
                        </div>
                        <div style="padding: 14px;">
                            <p>姓名 {{ lawyer.name }}</p>
                            <p>性别 {{ lawyer.gender }}</p>
                            <p>电话 {{ lawyer.contactNumber }} </p>
                            <p>地址 {{ lawyer.address }} </p>
                            <p>专长领域 {{ lawyer.expertise }} </p>
                            <a href="#" class="primary" @click="queryLawyerDetail(lawyer)">律师详情</a>
                            <a href="#" class="primary" @click="openChatDialog(lawyer)">开始咨询</a>
                        </div>
                    </el-card>
                </el-col>
            </div>
            <el-dialog
                    title="聊天对话框"
                    :visible.sync="dialogVisible"
                    width="50%">
                <div v-for="(message, index) in chatMessages" :key="index" >
                    <p v-if="message.messageFromUser" class="message user-message">
                        {{message.createTime}}<br>
                        <img v-if="message.messageFromUser" :src="['/files/' + user.avatar]" class="user-avatar">
                        {{ message.messageFromUser }}
                    </p>
                    <p v-if="message.messageFromLawyer" class="message system-message">
                        {{message.createTime}}<br>
                        <img v-if="message.messageFromLawyer " :src="['/files/' + lawyer.avatar]" class="user-avatar">
                        {{ message.messageFromLawyer }}
                    </p>
                </div>
                <input type="text" v-model="newMessage" @keyup.enter="sendMessage()" placeholder="请输入要咨询的问题">
            </el-dialog>


            <el-dialog title="律师详细信息" :visible.sync="dialogFormVisible" width="30%"
                       :close-on-click-modal="false">
                <el-descriptions class="margin-top" title="无边框列表" :column="3" >
                    <el-descriptions-item label="照片">
                        <img v-if="entity.avatar" :src="['/files/' + entity.avatar]"
                             style="height: 100px;width: 100px;display: block" class="avatar">
                    </el-descriptions-item>
                    <br>
                    <el-descriptions-item label="用户名">姓名: {{entity.name}}</el-descriptions-item>
                    <br>
                    <el-descriptions-item label="居住地">性别: {{entity.gender}}</el-descriptions-item>
                    <br>
                    <el-descriptions-item label="手机号">电话: {{entity.contactNumber}}</el-descriptions-item>
                    <br>
                    <el-descriptions-item label="邮箱">邮箱: {{entity.email}}</el-descriptions-item>
                    <br>
                    <el-descriptions-item label="出生日期">出生日期: {{entity.birth}}</el-descriptions-item>
                    <br>
                    <el-descriptions-item label="地址">地址: {{entity.address}}</el-descriptions-item>
                    <br>
                    <el-descriptions-item label="专长领域">专长领域: {{entity.expertise}}</el-descriptions-item>
                    <br>
                    <el-descriptions-item label="执业资格证书编号">执业资格证书编号: {{entity.licenseNumber}}</el-descriptions-item>
                    <br>
                    <el-descriptions-item label="执业资格证书颁发机构">执业资格证书颁发机构: {{entity.licenseIssuingAuthority}}</el-descriptions-item>
                    <br>
                    <el-descriptions-item label="执业资格证书颁发日期">执业资格证书颁发日期: {{entity.licenseIssueDate}}</el-descriptions-item>
                    <br>
                    <el-descriptions-item label="审核状态">审核状态: {{entity.isApproved}}</el-descriptions-item>
                    <br>
                </el-descriptions>

            </el-dialog>

        </el-col>
    </el-row>

</div>

<!--    js-->
<script src="../../js/jquery.min.js"></script>

<script src="../../js/vue.min.js"></script>
<script src="../../js/element.js"></script>

<script>
    new Vue({
        el: "#wrapper",
        data: {
            user: {},
            chatMessages:[],
            newMessage: '',
            dialogVisible: false,
            lawyerList:[],
            dialogFormVisible:false,
            entity:{},
            message:{},
            lawyer:{},
        },
        created() {
            $.ajax({url: '/api/user/session', method: "GET", async: false, success: (res) => {this.user = res.data || {}}})
            this.loadTable()
        },
        methods: {
            //注销登录
            logout() {
                $.get("/api/user/logout");
                sessionStorage.removeItem("user");
                location.href = "/page/end/login.html";
            },
            loadTable() {
                if(!this.user.id) {
                    this.$message({
                        message: "请登录！",
                        type: "warning"
                    })
                    return
                }
                $.get("/api/user/" + this.user.id).then(res => {
                    this.user = res.data
                })
                $.get("/api/lawyer").then(res=>{
                    console.log(res.data)
                    this.lawyerList = res.data;
                })
            },
            openChatDialog(lawyer) {
                this.lawyer = lawyer;
                this.loadData();
                this.connectWebSocket();
                this.dialogVisible = true;
            },
            formatDateTime(date) {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');

                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            },
            //加载聊天数据
            loadData(){
                // 模拟数据，这里可以根据需要初始化聊天对话框的内容
                $.get("/api/consultationRecord/history/"+this.lawyer.id).then(res=>{
                    this.chatMessages = res.data
                    if (this.chatMessages.length === 0){
                        this.chatMessages = [{
                            messageFromLawyer: '您好，我是'+this.lawyer.name+'律师，擅长的领域是'+this.lawyer.expertise+'，很高兴为您服务。请问有什么能帮助你的吗？',
                            createTime: this.formatDateTime(new Date()),
                        }]

                    }
                    console.log('this.chatMessages',this.chatMessages)
                })
            },
            connectWebSocket() {
                this.ws = new WebSocket('ws://localhost:9999/api/message/'+this.user.username);

                this.ws.onopen = () => {
                    console.log('WebSocket connected');
                };

                this.ws.onmessage = (event) => {
                    // 处理收到的消息
                    console.log(event)
                    console.log(JSON.parse(event.data));
                    this.chatMessages.push(JSON.parse(event.data));
                };

                this.ws.onclose = () => {
                    console.log('WebSocket disconnected');
                };
            },
            //发送消息
            sendMessage() {
                if (this.newMessage.trim() !== '') {
                    console.log("newMessage",this.newMessage)
                    console.log("this.lawyer",this.lawyer)
                    console.log("this.user",this.user)
                    this.message = {messageFromUser:this.newMessage,lawyerId:this.lawyer.id,lawyerName:this.lawyer.name,userId:this.user.id,userName:this.user.username}
                    this.chatMessages.push(this.message);
                    // 保存入库
                    this.save()
                    // 模拟系统回复
                    // setTimeout(() => {
                    //     this.chatMessages.push({ text: 'Your message is received.', sender: 'system' });
                    // }, 500);
                    this.newMessage = '';
                    this.message = {};
                }
            },
            queryLawyerDetail(person) {
                $.get("/api/lawyer/"+person.id).then(res=>{
                    console.log(res.data)
                    this.entity = res.data;
                })
                this.dialogFormVisible = true
            },
            save() {
                $.ajax({
                    url: "/api/consultationRecord/",
                    type: "POST",
                    contentType: "application/json",
                    data: JSON.stringify(this.message)
                }).then(res => {
                    if (res.code === '0') {
                        this.$message({
                            message: "消息发送成功",
                            type: "success"
                        });
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        })
                    }
                    this.loadData();
                })
            },
        }
    })
</script>
</body>
</html>
